package com.example.yqand4v1_1.service;

import com.example.yqand4v1_1.dto.AddNewsDiscussDTO;
import com.example.yqand4v1_1.dao.entity.NewsDiscuss;
import com.example.yqand4v1_1.dao.NewsDiscussMapper;
import com.example.yqand4v1_1.vo.NewsDiscussVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Service
public class NewsDiscussService {


    @Resource
    private NewsDiscussMapper newsDiscussMapper;

    @Resource
    private NewsService newsService;

    @Transactional(rollbackFor = Exception.class)
    public void addNewsDiscuss(AddNewsDiscussDTO data) {
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        String addTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // 校正时间
        newsDiscussMapper.add(data, data.getUserId(), data.getUsername(),addTime);
        newsService.addCommentNum(data.getNewsId());
    }

    // 新闻评论
    public List<NewsDiscussVO> getByNewsId(int newsId) {
        List<NewsDiscuss> newsDiscusses = newsDiscussMapper.getByNewsId(newsId);
        List<NewsDiscussVO> ret = new ArrayList<>();
        if (CollectionUtils.isEmpty(newsDiscusses)) {
            return ret; // 返回空表
        }
        // 评论与回复布局 回复为子对象
        newsDiscusses.forEach(e -> {
            NewsDiscussVO vo = new NewsDiscussVO();
            BeanUtils.copyProperties(e, vo);
            if (e.getPId() == null) {
                ret.add(vo);
            } else {
                ret.stream().filter(r -> Objects.equals(r.getId(), e.getPId())).findFirst().ifPresent(r -> {
                    r.getChildren().add(vo);
                });
            }
        });
        return ret;
    }
}
